<?php
// 1. 模型对应的是数据库中的表，一个数据表应该有一个模型
// 数据库表的名字：books  模型：单数
namespace Models;
class Book extends Model{

    public function addBook($title, $isbn, $publish) {
        $sql = 'insert into books(title, isbn, publish) values ("' . $title . '", "' . $isbn . '", "' . $publish . '")';
        return  $this->pdo->exec($sql);
    }

    public function getAllBooks() {
        $sql = 'select * from books order by id desc';
        $pdt = $this->pdo->query($sql); // PDOStatement 结果集对象
        return $pdt->fetchAll(\PDO::FETCH_ASSOC); // 遍历所属有的结果
    }

    public function deleteBook($book_id) {
        $sql = 'delete from books where id = ' . $book_id;

        return $this->pdo->exec($sql);
    }

    public function getBookById($id) {
        $sql = 'select * from books where id = ' . $id;
        $pdt = $this->pdo->query($sql);

        return $pdt->fetch(\PDO::FETCH_ASSOC);
    }

    public function updateBook($title, $isbn, $publish, $stock, $id) {
        $sql = 'update books set title = "' . $title . '", isbn = "' . $isbn . '", publish = "' . $publish . '", stock = ' . $stock . ' where id = ' . $id;
        return $this->pdo->exec($sql);
    }

    public function decrementStock($stock, $book_id) {
        $sql = 'update books set  stock = ' . $stock . ' where id = ' . $book_id;
        return $this->pdo->exec($sql);
    }
}